﻿using ICSharpCode.SharpZipLib.Zip;
using MengXunAppTool.DAL;
using MengXunAppTool.Helper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 自动升级工具
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private ConfigHelper configHelper = new ConfigHelper();
        private VerDAL verDAL = new VerDAL();
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Dictionary<string, string> dic = configHelper.ReadAll();
                string App = dic["App"];
                string customer = "盟讯";
                string product = "通用";
                string softwarename = "";
                if (App.Contains("发布"))
                {
                    softwarename = "软件发布平台";
                }
                else
                {
                    softwarename = "软件运行平台";
                }
                string lastVer = verDAL.GetLastVer(customer, product, softwarename);
                Sql3Helper.MX_AppVerRecord mX_VerRecord = verDAL.GetApp(customer, product, softwarename, lastVer);
                new Thread((Action) =>
                {
                    try
                    {
                        if (lastVer != dic["Version"])
                        {
                            string zip = Download(mX_VerRecord.FtpPath, System.Environment.CurrentDirectory.Substring(0, System.Environment.CurrentDirectory.LastIndexOf('\\')));
                            Process[] myproc = Process.GetProcesses();
                            foreach (Process item in myproc)
                            {
                                if (item.ProcessName.Contains(softwarename))
                                {
                                    item.Kill();
                                }
                            }
                            Decompress(zip, zip.Substring(0, zip.LastIndexOf('\\')), mX_VerRecord);
                            Bar.Dispatcher.Invoke((Action)delegate
                            {
                                Text.Text = "100%";
                                Bar.Value = 100;
                            });
                            configHelper.Write("Version", lastVer);
                        }
                        Thread.Sleep(1000);
                        Process process1 = new Process();
                        process1.StartInfo.WorkingDirectory = System.Environment.CurrentDirectory.Substring(0, System.Environment.CurrentDirectory.LastIndexOf('\\'));
                        process1.StartInfo.FileName = App;
                        process1.Start();
                        Dispatcher.Invoke((Action)delegate
                        {
                            this.Close();
                        });
                    }
                    catch (Exception ee)
                    {
                        Dispatcher.Invoke((Action)delegate
                        {
                            new View.MessageBoxView("错误！", ee.Message.ToString()).ShowDialog();
                           LogHelper.WriteLog(ee.ToString());
                            this.Close();
                        });
                    }

                }).Start();
            }
            catch (Exception ee)
            {
                new View.MessageBoxView("错误！", ee.Message.ToString()).ShowDialog();
               LogHelper.WriteLog(ee.ToString());
                this.Close();
            }

        }
        private string path = "ftp://cquni.com//";    //目标路径
        private string username = "yfgc";   //ftp用户名
        private string password = "yfgc";   //ftp密码
        public string Download(string fileName, string localPath)
        {
            try
            {
                FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
                req.Method = WebRequestMethods.Ftp.GetFileSize;
                req.UseBinary = true;
                req.Credentials = new NetworkCredential(username, password);
                req.UsePassive = false;
                FtpWebResponse res = (FtpWebResponse)req.GetResponse();
                long cl = res.ContentLength;
                Bar.Dispatcher.Invoke((Action)delegate
                {
                    Text.Text = "5%";
                    Bar.Value = 5;
                });
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(username, password);
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                Stream ftpStream = response.GetResponseStream();
                long lenth = 0;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);

                Bar.Dispatcher.Invoke((Action)delegate
                {
                    Text.Text = "10%";
                    Bar.Value = 10;
                });
                if (!Directory.Exists(localPath))
                {
                    Directory.CreateDirectory(localPath);
                }
                using (FileStream outputStream = new FileStream(localPath + fileName.Substring(fileName.LastIndexOf('\\')), FileMode.Create))
                {
                    ftpStream.ReadTimeout = 3000;
                    try
                    {
                        while (readCount > 0)
                        {
                            outputStream.Write(buffer, 0, readCount);
                            readCount = ftpStream.Read(buffer, 0, bufferSize);
                            lenth += readCount;
                            int value = (int)(lenth * 71 / cl) + 10;
                            Dispatcher.Invoke((Action)delegate
                            {
                                Text.Text = value + "%";
                                Bar.Value = value;
                            });
                        }
                    }
                    catch (Exception)
                    {
                    }
                    if (outputStream.Length < cl)
                    {
                        throw new Exception("文件下载失败");
                    }
                    ftpStream.Close();
                    outputStream.Close();
                    response.Close();
                    return outputStream.Name;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void Decompress(string GzipFile, string targetPath, Sql3Helper.MX_AppVerRecord mX_App)
        {
            string directoryName = targetPath;
            if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录    
            string CurrentDirectory = directoryName;
            byte[] data = new byte[2048];
            int size = 2048;
            ZipEntry theEntry = null;
            long count;
            using (FileStream fsFile = new FileStream(GzipFile, FileMode.OpenOrCreate))
            {
                ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(fsFile);
                count = zipFile.Count;
                fsFile.Flush();
                fsFile.Close();
            }
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
            {
                int num = 0;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    num++;
                    if (theEntry.IsDirectory)
                    {// 该结点是目录    
                        if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
                    }
                    else
                    {

                        if (theEntry.Name != String.Empty)
                        {
                            //  检查多级目录是否存在  
                            if (theEntry.Name.Contains("/"))
                            {
                                string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("/") + 1);
                                string[] changeFiles = new string[] { };
                                if (mX_App.ConfigPathList != null)
                                {
                                    changeFiles = mX_App.ConfigPathList.Split(';');
                                }
                                if (parentDirPath.Equals("Update/") || changeFiles.Contains("\\" + theEntry.Name))
                                {
                                    continue;
                                }

                                if (!Directory.Exists(CurrentDirectory + "\\" + parentDirPath))
                                {
                                    Directory.CreateDirectory(CurrentDirectory + "\\" + parentDirPath);
                                }
                            }

                            //解压文件到指定的目录    
                            using (FileStream streamWriter = File.Create(CurrentDirectory + "\\" + theEntry.Name))
                            {
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size <= 0) break;
                                    streamWriter.Write(data, 0, size);
                                }
                            }
                        }
                    }
                    int value = (int)(num * 21 / count) + 80;
                    Dispatcher.Invoke((Action)delegate
                    {
                        Text.Text = value.ToString("0") + "%";
                        Bar.Value = value;
                    });
                }
                s.Close();
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
